﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWeb.Data;
using MyWeb.Business;
using MyWeb.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MyWeb.Admin
{
	public partial class User : System.Web.UI.Page
	{
		static bool Insert = false;
        static string Password = "";
		static string Id = "";
        static string Level = "";
		private string LangAdm = "";
        Database db = DatabaseFactory.CreateDatabase();
		protected void Page_Load(object sender, EventArgs e)
		{
			LangAdm = Global.GetLangAdm();
            if (!IsPostBack)
            {
                lbtDeleteT.Attributes.Add("onClick", "javascript:return confirm('Bạn có muốn xóa?');");
				lbtDeleteB.Attributes.Add("onClick", "javascript:return confirm('Bạn có muốn xóa?');");
				NumberClass.OnlyInputNumber(txtOrd);
				BindGrid();
			}
		}

		private void BindGrid()
		{
            if (Common.StringClass.Check(Session["IsAdmin"]) && Common.StringClass.Check(Session["UserId"]))
            {
                grdUser.DataSource = UserService.User_GetByTop("", "Admin >= '" + Session["IsAdmin"] + "' and len(Level) >= " + Business.UserService.User_GetById(Session["UserId"].ToString())[0].Level.Length, "Ord, Id");
            }
            else
            {
                grdUser.DataSource = UserService.User_GetByTop("", "Admin >= '1'" + Business.UserService.User_GetById(Session["UserId"].ToString())[0].Level.Length, "Ord, Id");
            }
            //grdUser.DataSource = UserService.User_GetByTop("", "Admin <= '" + Session["IsAdmin"] + "' and len(Level) >= " + Business.UserService.User_GetById(Session["UserId"].ToString())[0].Level.Length, "Ord, Id");
			grdUser.DataBind();
			if (grdUser.PageCount <= 1)
			{
				grdUser.PagerStyle.Visible = false;
			}
		}

		protected void grdUser_ItemDataBound(object sender, DataGridItemEventArgs e)
		{
			ListItemType itemType = e.Item.ItemType;
			if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
			{
				if (itemType == ListItemType.Header)
				{
					object checkBox = e.Item.FindControl("chkSelectAll");
					if ((checkBox != null))
					{
						((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
					}
				}
				else
				{
					string tableRowId = grdUser.ClientID + "_row" + e.Item.ItemIndex.ToString();
					e.Item.Attributes.Add("id", tableRowId);
					object checkBox = e.Item.FindControl("chkSelect");
					if ((checkBox != null))
					{
						e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
						e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
						((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
					}
				}
			}
		}

		protected void grdUser_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
		{
			grdUser.CurrentPageIndex = e.NewPageIndex;
			BindGrid();
		}

		protected void grdUser_ItemCommand(object source, DataGridCommandEventArgs e)
		{
			string strCA = e.CommandArgument.ToString();
			switch (e.CommandName)
			{
				case "AddSub":
                    Id = strCA;
                    PermissionButton_Click(source, e);
					break;
				case "Edit":
					Insert = false;
                    txtId.Value = strCA;
                    List<Data.User> listE = UserService.User_GetById(strCA);
					Level = listE[0].Level.Substring(0, listE[0].Level.Length - 5);
					txtName.Text = listE[0].Name;
					txtUsername.Text = listE[0].Username;
                    ddlAdmin.Text = listE[0].Admin;
					txtPassword.Text = "";
                    Password = listE[0].Password;
					txtOrd.Text = listE[0].Ord;
					chkActive.Checked = listE[0].Active == "1" || listE[0].Active == "True";
					pnView.Visible = false;
					pnUpdate.Visible = true;
					break;
				case "Active":
					string strA = "";
					string str = e.Item.Cells[2].Text;
					strA = str == "1" ? "0" : "1";
                    db.ExecuteNonQuery(System.Data.CommandType.Text, "Update [User] set Active=" + strA + "  Where Id='" + strCA + "'");
					BindGrid();
					break;
				case "Delete":
					UserService.User_Delete(strCA);
					BindGrid();
					break;
			}
		}

		protected void AddButton_Click(object sender, EventArgs e)
		{
			pnUpdate.Visible = true;
			ControlClass.ResetControlValues(this);
			pnPermission.Visible = false;
            pnView.Visible = false;
			Insert = true;
		}

        protected void PermissionButton_Click(object sender, EventArgs e)
        {
            pnPermission.Visible = true;
            ControlClass.ResetControlValues(this);
            pnView.Visible = false;
            pnUpdate.Visible = false;
            Insert = true;
            List<Data.ModulePermission> list = Business.PermissionService.Permission_GetByAll(Id);
            rptPermission.DataSource = list;
            rptPermission.DataBind();
        }

		protected void DeleteButton_Click(object sender, EventArgs e)
		{
			DataGridItem item = default(DataGridItem);
			for (int i = 0; i < grdUser.Items.Count; i++)
			{
				item = grdUser.Items[i];
				if (item.ItemType == ListItemType.AlternatingItem | item.ItemType == ListItemType.Item)
				{
					if (((CheckBox)item.FindControl("ChkSelect")).Checked)
					{
						string strId = item.Cells[1].Text;
						UserService.User_Delete(strId);
					}
				}
			}
			grdUser.CurrentPageIndex = 0;
			BindGrid();
		}

		protected void RefreshButton_Click(object sender, EventArgs e)
		{
			BindGrid();
		}

        protected Boolean CheckActivePermission(string usertype)
		{
			return usertype.Equals("0") ? true : false;
		}

		protected void Update_Click(object sender, EventArgs e)
		{
			if (Page.IsValid){
				Data.User obj = new Data.User();
				obj.Id = txtId.Value;
				obj.Name = txtName.Text;
				obj.Username = txtUsername.Text;
				obj.Level = Level + "00000";
				obj.Admin = ddlAdmin.SelectedValue;
				obj.Ord = txtOrd.Text != "" ? txtOrd.Text : "1";
				obj.Active = chkActive.Checked ? "1" : "0";
                obj.Password = txtPassword.Text != "" || Common.StringClass.Check(txtId.Value) == false ? StringClass.Encrypt(txtPassword.Text) : Password;
                if (Insert == true){
					UserService.User_Insert(obj);
				}
				else{
					UserService.User_Update(obj);
				}
				BindGrid();
				pnView.Visible = true;
				pnUpdate.Visible = false;
				Level= "";
				Insert = false;
			}
		}

		protected void Back_Click(object sender, EventArgs e)
		{
			pnView.Visible = true;
			pnUpdate.Visible = false;
			Level= "";
			Insert = false;
		}

        protected void Update_Permission(object sender, EventArgs e)
        {

        }

        protected void Back_Permission(object sender, EventArgs e)
        {

        }

        protected void cvdUserName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true;
            string sql = "";
            if (txtId.Value.Length > 0){
                sql = "select count(*) from [user] where Id <>'" + txtId.Value + "' and username='" + txtUsername.Text + "'";
            }else{
                sql = "select count(*) from [user] where username='" + txtUsername.Text + "'";
            }
            int rCount = Convert.ToInt16(db.ExecuteScalar(System.Data.CommandType.Text, sql));
            List<Data.User> list = Business.UserService.User_GetByAll();
            if (rCount > 0)
            {
                args.IsValid = false;
                txtUsername.Text = "";
                txtUsername.Focus();
            }
        }
	}
}